package com.LeeCode;

/**
 * 得分最高的最小轮调
 */

public class Code798 {
    public static void main(String[] args) {
        int[] nums = {1, 3, 0, 2, 4};
        System.out.println(new Code798().bestRotation(nums));
    }

    public int bestRotation(int[] nums) {
        int n = nums.length;
        int[] diff = new int[n + 1];

        for (int i = 0; i < n; i++) {
            int p1 = n + i - nums[i], p2 = i - nums[i];
            if (p1 > i) {
                diff[i + 1]++;
                if (p1 + 1 <= n) diff[p1 + 1]--;
            }
            if (p2 >= 0) {
                diff[0]++;
                diff[p2 + 1]--;
            }
        }
        int sum = 0, bestK = 0, maxScore = -1;

        for (int k = 0; k < n; k++) {
            sum += diff[k];
            if (sum > maxScore) {
                maxScore = sum;
                bestK = k;
            }
        }


        return bestK;
    }
}
